package com.xbongbong.paas.script.controller;

import com.alibaba.fastjson.JSON;
import com.xbongbong.paas.enums.PlatFormEnum;
import com.xbongbong.paas.help.menu.InitMenuHelp;
import com.xbongbong.paas.pojo.dto.MigrateSoukeDTO;
import com.xbongbong.paas.script.pojo.dto.BundleInitDTO;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.wrap.XbbResponse;
import com.xbongbong.pro.appmodule.pojo.dto.AppModuleOpenDTO;
import com.xbongbong.pro.config.ProBaseConfig;
import com.xbongbong.pro.constant.XbbProConstant;
import com.xbongbong.pro.domain.entity.AppModuleEntity;
import com.xbongbong.pro.enums.ModuleAppOperateEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.enums.menu.enums.SystemAppMenuEnum;
import com.xbongbong.pro.menu.pojo.dto.MenuInitDTO;
import com.xbongbong.pro.script.pojo.vo.ScriptVO;
import com.xbongbong.saas.model.AppModuleModel;
import com.xbongbong.saas.script.service.MigrateSoukeService;
import com.xbongbong.saas.service.AppModuleService;
import org.springframework.http.MediaType;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.List;
import java.util.Objects;

/**
 * @author 吴峰
 * @version v1.0
 * @date 2020/5/8 11:09
 * @since v1.0
 */
@RestController
@RequestMapping(XbbProConstant.API_ROOT_PREFIX+"/script/init")
public class AppInitScriptController {

    @Resource
    private ProBaseConfig proBaseConfig;

    @Resource
    private InitMenuHelp initMenuHelp;
    
    @Resource
    private AppModuleService appModuleService;
    
    @Resource
    private AppModuleModel appModuleModel;
    @Resource
    private MigrateSoukeService migrateSoukeService;

    @RequestMapping(value = "/app", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String explains(@RequestBody @Valid MenuInitDTO menuInitDTO, BindingResult br) throws XbbException {
        if (!proBaseConfig.getXbbCode().equals(menuInitDTO.getXbbCode())) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100006);
        }
        XbbResponse<ScriptVO> response;
        if ( br.hasErrors() ) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                menuInitDTO.setCompanyInit(1);
                initMenuHelp.menuInit(menuInitDTO);
                ScriptVO scriptVO = new ScriptVO();
                scriptVO.setMsg("初始化成功");
                response = new XbbResponse<>(scriptVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response);
    }
    
    @RequestMapping(value = "/bundleInit", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String bundleInit(@RequestBody @Valid BundleInitDTO bundleInitDTO, BindingResult br) throws XbbException {
        if (!proBaseConfig.getXbbCode().equals(bundleInitDTO.getXbbCode())) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100006);
        }
        XbbResponse<ScriptVO> response;
        if ( br.hasErrors() ) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                List<String> corpidList = bundleInitDTO.getCorpidList();
                AppModuleEntity appModule = appModuleModel.getByAlias(SystemAppMenuEnum.BUNDLE.getAlias());
                for ( String corpid : corpidList ) {
                    AppModuleOpenDTO openDTO = new AppModuleOpenDTO();
                    openDTO.setCorpid(corpid);
                    openDTO.setUserId("");
                    openDTO.setPlatform(PlatFormEnum.WEB.getValue());
                    openDTO.setAlias(appModule.getAlias());
                    openDTO.setOperate(ModuleAppOperateEnum.START.getAlias());
                    openDTO.setAppModuleId(appModule.getId());
                    appModuleService.open(openDTO);
                }
                ScriptVO scriptVO = new ScriptVO();
                scriptVO.setMsg("初始化成功");
                response = new XbbResponse<>(scriptVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response);
    }

    @RequestMapping(value = "/marketActivityInit", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String marketActivityInit(@RequestBody @Valid BundleInitDTO bundleInitDTO, BindingResult br) throws XbbException {
        if (!proBaseConfig.getXbbCode().equals(bundleInitDTO.getXbbCode())) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100006);
        }
        XbbResponse<ScriptVO> response;
        if ( br.hasErrors() ) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                List<String> corpidList = bundleInitDTO.getCorpidList();
                AppModuleEntity appModule = appModuleModel.getByAlias(SystemAppMenuEnum.MARKET_MANAGEMENT.getAlias());
                for ( String corpid : corpidList ) {
                    AppModuleOpenDTO openDTO = new AppModuleOpenDTO();
                    openDTO.setCorpid(corpid);
                    openDTO.setUserId("");
                    openDTO.setPlatform(PlatFormEnum.WEB.getValue());
                    openDTO.setAlias(appModule.getAlias());
                    openDTO.setOperate(ModuleAppOperateEnum.START.getAlias());
                    openDTO.setAppModuleId(appModule.getId());
                    appModuleService.open(openDTO);
                }
                ScriptVO scriptVO = new ScriptVO();
                scriptVO.setMsg("初始化成功");
                response = new XbbResponse<>(scriptVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response);
    }

    /**
     * 迁移旧搜客到新搜客（工商查询＋搜客）
     * 第一期：工商查询
     * 第二期：搜客
     *
     * @param migrateSoukeDTO
     * @param br
     * @return
     * @throws XbbException
     */
    @RequestMapping(value = "/migrateSouke", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String migrateSouke(@RequestBody @Valid MigrateSoukeDTO migrateSoukeDTO, BindingResult br) throws XbbException {
        if (!proBaseConfig.getXbbCode().equals(migrateSoukeDTO.getXbbCode())) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100006);
        }
        XbbResponse<ScriptVO> response;
        if ( br.hasErrors() ) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                ScriptVO scriptVO = migrateSoukeService.migrateSouke(migrateSoukeDTO);
                response = new XbbResponse<>(scriptVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response);
    }

}
